package cn.com.fuhuitong.http

import androidx.annotation.NonNull
import cn.com.fuhuitong.entity.Error
import cn.com.fuhuitong.entity.MainBean
import com.blankj.utilcode.util.LogUtils
import org.greenrobot.eventbus.EventBus

open class ResponseSubscribeListener<Response : BaseResponse>(
    private val listener: SubscribeListener<Response>
) {

    open fun onStart() {
        listener.onStart()
    }

    open fun onSuccess(resp: Response) {
        val value = HttpResponse<Response>()

        when (resp.code) {
            1 -> value.apply {
                status = HttpResponseStatus.Status.SUCCESS
                response = resp
                listener.onSuccess(resp)
            }
            else -> value.apply {
                status = HttpResponseStatus.Status.FAILURE
                val exception = ResponseException(resp.code, resp.msg)
                this.exception = exception
                listener.onFailure(exception)
            }

        }
    }

    open fun onFailure(@NonNull throwable: Throwable) {
        val value = HttpResponse<BaseResponse>()
        value.run {
            status = HttpResponseStatus.Status.FAILURE
            val exception: ResponseException =
                ExceptionHandle.handleThrowable(throwable)
            this.exception = exception
            if (exception.code == 401) {
                EventBus.getDefault().post(MainBean(type = Error.ERROR_401, data = null))
            }
            listener.onFailure(exception)
        }
    }

}